package com.wb.base.refreshview;

import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.squareup.picasso.Picasso;

public class BaseViewHolder extends RecyclerView.ViewHolder {
    View rootView;

    private SparseArray<View> mViews;


    public <T extends View> T $(int resId) {

        View view = mViews.get(resId);
        if (view == null) {
            view = rootView.findViewById(resId);
            mViews.put(resId, view);
        }
        return (T) view;
    }

    public <T extends View> T getView(int resId) {
        return $(resId);
    }


    public <T extends View> T findView(int resId) {
        return $(resId);
    }

    public BaseViewHolder(View rootView) {
        super(rootView);
        this.rootView = rootView;
        mViews = new SparseArray<View>();
    }

    public ImageView getImgView(int resId) {
        return findView(resId);
    }

    public BaseViewHolder setText(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text == null ? "" : text);
        return this;
    }

    public BaseViewHolder setText(int viewId, int text) {
        TextView tv = getView(viewId);
        tv.setText(text + "");
        return this;
    }

    public BaseViewHolder setText(int viewId, float text) {
        TextView tv = getView(viewId);
        tv.setText(text + "");
        return this;
    }

    public BaseViewHolder setText(int viewId, double text) {
        TextView tv = getView(viewId);
        tv.setText(text + "");
        return this;
    }

    public BaseViewHolder setImageResource(int viewId, int resId) {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    public BaseViewHolder setOnClickListener(int viewId,
                                             View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public BaseViewHolder hide(int viewId) {
        View view = getView(viewId);
        view.setVisibility(View.GONE);
        return this;
    }

    public BaseViewHolder invisible(int viewId) {
        View view = getView(viewId);
        view.setVisibility(View.INVISIBLE);
        return this;
    }

    public BaseViewHolder show(int viewId) {
        View view = getView(viewId);
        view.setVisibility(View.VISIBLE);
        return this;
    }

    public BaseViewHolder load(int res, String url) {
        ImageView imageView = getImgView(res);

        if (imageView instanceof SimpleDraweeView) {
            ((SimpleDraweeView) imageView).setImageURI(Uri.parse(url));
        } else {
            Picasso.with(imageView.getContext()).load(url).into(imageView);
        }
        return this;
    }

}